package com.imooc.core.utils;

import java.text.DateFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class CommonUtils {
	// 默认时间格式 2011-01-01 11:12:13
	private static final String DEFAULT_DATA_FORMAT = "yyyy-MM-dd HH:mm:ss";

	public static Date parseDateTime(String s) throws ParseException {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return format.parse(s);
	}

	public static boolean isDateBefore(String date) {
		try {
			Date date1 = new Date();
			DateFormat df = DateFormat.getDateTimeInstance();
			return date1.before(df.parse(date));
		} catch (ParseException e) {
			System.out.print(e.getMessage());
			return false;
		}
	}

	public static boolean isDateAfter(String date) {
		try {
			Date date1 = new Date();
			DateFormat df = DateFormat.getDateTimeInstance();
			return date1.after(df.parse(date));
		} catch (ParseException e) {
			System.out.print(e.getMessage());
			return false;
		}
	}

	/**
	 * 获取当前系统时间，格式 yyyy-MM-dd HH:mm:ss
	 * 
	 * @return
	 */
	public static String getCurrentTime() {
		String result = String.format("%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS", Calendar.getInstance());
		return result;
	}

	/**
	 * 通过指定格式返回当前系统时间<br />
	 * 格式不支持时将使用默认格式:yyyy-MM-dd HH:mm:ss<br />
	 * 
	 * @param format
	 * @return
	 */
	public static String getCurrentTime(String format) {
		String result = "";
		SimpleDateFormat sDateFormat = new SimpleDateFormat(format);
		try {
			result = sDateFormat.format(new Date());
		} catch (Exception e) {
			sDateFormat = new SimpleDateFormat(DEFAULT_DATA_FORMAT);
			result = sDateFormat.format(new Date());
		}
		return result;
	}
	
	/**
	 * 装成百分比
	 * @param allsum
	 * @param v
	 * @return
	 */
	public static String numberFormat(Object allsum, Object v) {
		NumberFormat numberFormat = NumberFormat.getInstance();
		numberFormat.setMaximumFractionDigits(2);
		return numberFormat.format((Double.parseDouble(allsum.toString()) / Double.parseDouble(v.toString()) * 100)) + "%";
	}
}
